import React, { useRef, useState, useEffect, useCallback, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { Card, Button, Tabs, Typography, List, Tag, message } from 'antd';
import { HistoryOutlined, MessageOutlined } from '@ant-design/icons';
import { ChatRef } from '../../../components/chat/chatType';
import { Message } from '@douyinfe/semi-foundation/lib/es/chat/foundation';
import { getSessionHistory, getSessionMessages } from '../../../apis/front/assistant';
import { Agent_System_Chat } from '../../../globals/agent';
const { TabPane } = Tabs;

import ChatCom from '../../../components/chat/Chat';

import styles from './AIAssistant.module.css';

const AIAssistantPage: React.FC = observer(() => {
  // 引用聊天组件
  const chatRef = useRef<ChatRef>(null);
  
  // 状态
  const [chatHistory, setChatHistory] = useState<Message[]>([]);
  const [activeTab, setActiveTab] = useState('chat');
  const [historyLoading, setHistoryLoading] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize] = useState(10);
  const [hasMore, setHasMore] = useState(true);

  // 绑定Chat组件的ref
  const handleBindChatRef = useCallback((ref: React.RefObject<ChatRef>) => {
    console.log('Chat component ref bound');
  }, []);


  // 获取历史消息
  const fetchHistory = useCallback(async (reset = false) => {
    setHistoryLoading(true);
    try {
      const res = await getSessionHistory(Agent_System_Chat, pageNum, pageSize) as any;
      if (res && res.status && res.code === 200) {
        const records = res.data.records || [];
        setChatHistory(prev => reset ? records : [...prev, ...records]);
        const total = res.data.total || 0;
        setHasMore(pageNum * pageSize < total);
      }
    } finally {
      setHistoryLoading(false);
    }
  }, [Agent_System_Chat, pageNum, pageSize]);


  // 点击历史会话，获取并渲染消息
  const handleHistoryClick = useCallback(async (item: any) => {
    if (!item.id) return;
    
    const res = await getSessionMessages(item.id) as any;
    if (res && res.status && res.code === 200) {
      const data = res.data;
      if(data.success){
        const messages = (res.data.records || []).map((msg: any) => ({
          id: String(msg.id),
          role: msg.role,
          content: msg.content,
          createAt: new Date(msg.createTime).getTime(),
          isUser: msg.role === 'user',
        }));
        chatRef.current?.setHistoryMessages?.(messages);
        await chatRef.current?.changeSession?.(item.sessionId);
      }else{
        message.error(data.message);
      }
    }
  }, []);

  // 接收消息更新
  const handleMessage = useCallback((message: Message, sessionId: string, chatId: string, params: any) => {
    if(sessionId && !chatHistory.some(m => m.sessionId === message.sessionId)) {
      const newChat : any = {
        id: chatId,
        sessionId,
        title: params.userMessage
      }
      const updatedHistory = [newChat, ...chatHistory.slice(0, -1)];
      setChatHistory(updatedHistory);
    }
  }, [chatHistory]);

  // 加载更多
  const handleLoadMore = useCallback(() => {
    setPageNum(prev => prev + 1);
  }, []);

  useEffect(() => {
    fetchHistory(pageNum === 1);
    // eslint-disable-next-line
  }, [fetchHistory, pageNum]);

  const handleNewChat = useCallback(() => {
    chatRef?.current?.newChat();
  },[])
  
  // 渲染历史记录
  const renderHistory = useMemo(() => (
    <Card 
      title={<><div className={styles['ai-assistant-history-header']}>
        <div><HistoryOutlined /><span className={styles['ai-assistant-history-header-title']}>对话历史</span></div>
        <button className={styles['ai-assistant-history-newChat']} onClick={handleNewChat}>+ 新对话</button>
      </div></>} 
      size="small"
    >
      <List
        loading={historyLoading}
        dataSource={chatHistory}
        renderItem={item => (
          <List.Item onClick={() => handleHistoryClick(item)} style={{ cursor: 'pointer' }}>
            <Tag color="blue">会话</Tag>
            <Typography.Text ellipsis className={styles['ai-assistant-history-text']}>
              <div>{item.title}</div>
            </Typography.Text>
          </List.Item>
        )}
        locale={{ emptyText: '暂无对话历史' }}
      />
      {hasMore && (
        <div style={{ textAlign: 'center', marginTop: 8 }}>
          <Button loading={historyLoading} onClick={handleLoadMore} type="link">加载更多</Button>
        </div>
      )}
    </Card>
  ), [chatHistory, historyLoading, handleHistoryClick, hasMore, handleLoadMore]);

  const items = [  
    {  
      label: "对话",  
      key: "chat",        
      children: <></>, 
    },  
  ];
  return (
    <div className={styles['ai-assistant-root']}>
      
      {/*<Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={items}
        className={styles['ai-assistant-tabs']}
      />*/}
          <div className={styles['ai-assistant-chat-row']}>
            <div className={styles['ai-assistant-chat-main']}>
              {<ChatCom 
                ref={chatRef}
                agentId={Agent_System_Chat}
                bindRef={handleBindChatRef}
                onMessage={handleMessage}
                className={styles['ai-assistant-chat-component']}
              />}
            </div>
            
            <div className={styles['ai-assistant-chat-side']}>
              {renderHistory}
            </div>
          </div>
        

    </div>
  );
});

export default AIAssistantPage; 